<template>
  <div class="app-container" v-loading="loading">
    <el-dialog :title="prop.title" :visible.sync="prop.open" width="800px" :close-on-click-modal="false" :show-close="false" destroy-on-close append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row v-if="prop.typeId===experienceType.EDUCATE">
          <el-col :span="24">
            <el-form-item label="就读学校" prop="employeeExperienceOrganization">
              <el-input v-model="form.employeeExperienceOrganization" placeholder="请输入就读学校" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="prop.typeId===experienceType.WORK">
          <el-col :span="24">
            <el-form-item label="所在组织机构" prop="employeeExperienceOrganization">
              <el-input v-model="form.employeeExperienceOrganization" placeholder="请输入就读学校" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="经历时间" prop="range">
              <el-date-picker
                v-model="form.range"
                type="daterange"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="prop.typeId===experienceType.EDUCATE">
          <el-col :span="12">
            <el-form-item label="所获学历" prop="employeeExperienceEducation">
              <el-select v-model="form.employeeExperienceEducation" placeholder="请选择所获学历">
                <el-option
                  v-for="item in educations"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="经历内容" prop="employeeExperienceContent">
              <el-input type="textarea" v-model="form.employeeExperienceContent" placeholder="1-300字符" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="相关附件">
              <el-upload
                :action="action"
                :on-remove="delFile"
                :headers="headers"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <span slot="tip" style="color:red;margin-left: 5px;">单个文件不超过200m</span>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="saveLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {add,edit,getDetail} from '@/api/employee/employeeExperience/employeeExperience.js'
import {uploadUrl,uploadHeaders,deleteFile } from '@/api/file/file.js'
import {commonFileType} from '@/utils/constants/common/constants.js'
export default {
  name: "ExperienceEdit",
  dicts: [],
  components: {},
  props:{
    prop:{
      type:Object,
      default:function(){
        return {
          title:'新增经历',
          employeeExperienceId:null,
          typeId:null,
          employeeId:null,
          open:false
        }
      }
    }
  },
  data() {
    return {
      saveLoading:false,
      open:this.prop.open,
      loading:false,
      isEdit:false,
      experienceType:{
        WORK:"0",//工作经历,
        EDUCATE:"1",//教育学习经历,
        FOREIGN:"2", // 海外经历
      },
      educations:[
        {value:'博士',label:'博士'},
        {value:'硕士',label:'硕士'},
        {value:'本科',label:'本科'},
        {value:'大专',label:'大专'},
        {value:'中专',label:'中专'}
      ],
      form: {
        employeeId:this.prop.employeeId,
        employeeExperienceTypeId:this.prop.typeId,
        employeeExperienceId:this.prop.employeeExperienceId,
        employeeExperienceStartTime:null,
        employeeExperienceEndTime:null,
        employeeExperienceContent:null,
        employeeExperienceEducation:null,
        employeeExperienceOrganization:null,
        range:[],
        fileIds:[],
      },
      // 表单校验
      rules: {
        employeeExperienceStartTime: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        employeeExperienceEndTime: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ],
        employeeExperienceContent: [
          { required: true, message: "请输入经历内容", trigger: "blur" }
        ],
        employeeExperienceOrganization: [
          { required: true, message: "请输入组织机构", trigger: "blur" }
        ],
        range:[
          {required:true,message:"请选择经历时间",trigger: "change" }
        ]
      },
      action:uploadUrl,
      fileType:commonFileType,
      fileSize:200,
      oldFileList:[],
      fileList:[],
      headers:uploadHeaders,
    };
  },
  methods: {
    getDetail(){
      getDetail({employeeExperienceId:this.prop.employeeExperienceId,employeeExperienceTypeId:this.prop.typeId}).then(res =>{
        let data = res.data
        if(data.files!==null){
          data.experience.fileIds = data.files.map(item =>item.fileId)
          this.fileList = data.files.map(item =>{
            return {fileId:item.fileId,name:item.fileOriginalName}
          })
        }else{
          data.experience.fileIds = []
          console.log('经历详情中附件信息不存在')
        }
        this.form = data.experience
        this.form.range = [this.form.employeeExperienceStartTime,this.form.employeeExperienceEndTime]
      }).catch(err =>{
        console.log('查询经历详情失败，原因：',err)
      })
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 上传成功回调
    handleUploadSuccess(res, file,fileList) {
      if(res.code === 200){
        this.form.fileIds.push(res.data)
      }else{
        this.$message.error('上传附件失败，请稍后再试')
      }
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传附件失败, 请稍后再试");
    },
    delFile(file,fileList){
      if(file.fileId || file.response){
        let fileId = null
        if(file.fileId){
          fileId = file.fileId
        }else{
          fileId = file.response.data
        }
        //删除已提交文件
        if(fileId!==null){
          deleteFile({fileId:fileId}).then(res =>{
            let delIndex = this.form.fileIds.findIndex(item =>item === fileId)
            if(delIndex>-1){
              this.form.fileIds.splice(delIndex,1)
            }
            let fileDelIndex = this.fileList.findIndex(item =>item.fileId === fileId)
            if(fileDelIndex>-1){
              this.fileList.splice(fileDelIndex,1)
            }
          }).catch(err =>{
            console.log('删除文件失败，原因：',err)
            this.fileList = this.oldFileList
          })
        }
      }
    },
    setFormData(){
      let {range,fileIds,...experience} = this.form
      experience.employeeExperienceStartTime = range[0]
      experience.employeeExperienceEndTime = range[1]
      let files = fileIds.map(item => {
        return {fileId:item}
      })
      return {files:files,experience:experience}
    },
    /** 提交按钮 */
    submitForm: function() {
      this.saveLoading = true
      this.$refs["form"].validate(valid => {
        if (valid) {
          let formData = this.setFormData()
          if (this.isEdit) {
            edit(formData).then(response => {
              this.saveLoading = false
              this.$modal.msgSuccess("修改成功");
              this.cancel(true)
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          } else {
            add(formData).then(response => {
              this.saveLoading = false
              this.$modal.msgSuccess("新增成功");
              this.cancel(true)
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          }
        }else{
          this.saveLoading = false
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        employeeId:null,
        employeeExperienceTypeId:null,
        employeeExperienceId:null,
        employeeExperienceStartTime:null,
        employeeExperienceEndTime:null,
        employeeExperienceContent:null,
        employeeExperienceEducation:null,
        employeeExperienceOrganization:null,
        fileIds:[],
      };
      this.isEdit = false
    },
    // 取消按钮
    cancel(isEdit) {
      this.$emit('close',isEdit)
    },
  },
  mounted() {
    if(this.prop.employeeExperienceId){
      this.isEdit = true
      this.getDetail()
    }
  },
  updated() {
  },
};
</script>
<style scoped>

</style>
